package cn.edu.ljl;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

public class ValidataCode {

    private int width =150;
    private int high  =50;
    private int count =4;
    private int frontHigh =40;
    private BufferedImage codeImage =null;
    private String codeString = null;
    private char[] codeSequence = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
            'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

    public ValidataCode(){
        this.createCode();
    }

    private void createCode() {

        Random random =new Random();

        //设置验证图片参数
        BufferedImage bufferedImage = new BufferedImage(width,high,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.ORANGE);//设置验证码的背景颜色
        graphics.fillRect(0,0,width,high);

        //设置字体
        Font font = new Font("Fixedsys",Font.BOLD,frontHigh);
        graphics.setFont(font);

        //设置验证码边框
        graphics.setColor(Color.LIGHT_GRAY);
        graphics.drawRect(0,0,width-1,high-1);

        //随机产生验证码
        StringBuffer randomCode = new StringBuffer();
        for(int i=0;i<count;i++){
            String code = String.valueOf(codeSequence[random.nextInt(this.codeSequence.length)]);
            graphics.setColor(this.randomColor());
            graphics.drawString(code,(i+1)*(this.width/(this.count+2)),frontHigh-2);
            randomCode.append(code);
        }

        //产生干扰线
        for(int i=0;i<50;i++){
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(high);
            int x2 = random.nextInt(width/4);
            int y2 = random.nextInt(high/4);
            graphics.setColor(this.randomColor());
            graphics.drawLine(x1,y1,x1+x2,y1+y2);
        }

        this.codeString = randomCode.toString();
        this.codeImage  =bufferedImage;
    }

    //随机产生颜色
    private Color randomColor() {
        Random random = new Random();

        int red = random.nextInt(255);
        int green = random.nextInt(255);
        int blue = random.nextInt(255);
        return new Color(red,green,blue);
    }

    public void outputCodeImage(FileOutputStream path) throws IOException {
        FileOutputStream fileOutputStream =new FileOutputStream(String.valueOf(path));
        this.outputCodeImage(fileOutputStream);
    }

    public void outputCodeImage(OutputStream outputStream) throws IOException {
        ImageIO.write(this.codeImage,"png",outputStream);
    }

    public String getCodeString(){
        return  this.codeString;
    }

}
